import React, { useState } from 'react';
import { ImagePreview, Button, List, Toast, PullRefresh } from 'react-vant';
import './index.css';
import { getDefaultAvatarPath } from '@/utils/common';

const CommentComponent: React.FC<CommentComponentProps> = ({
  comments,
  finish,
  onLoad,
  onRefresh,
  onAdd,
}) => {
  const [showReplyBox, setShowReplyBox] = useState<number | null>(null);
  const [replyContent, setReplyContent] = useState('');
  const [previewImages, setPreviewImages] = useState<string[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [initialPosition, setInitialPosition] = useState(0);

  const handleImageClick = (images: string[], index: number) => {
    setPreviewImages(images);
    setInitialPosition(index);
    setShowPreview(true);
  };

  const handleReply = (commentId: number) => {
    setShowReplyBox((prev) => (prev === commentId ? null : commentId));
    setReplyContent('');
  };

  const handleSubmitReply = async (commentId: number, commentAccountName: string) => {
    if (!replyContent.trim()) {
      Toast.fail('回复内容不能为空');
      return;
    }

    try {
      await onAdd({ content: replyContent.trim(), commentId, commentAccountName });
      setReplyContent('');
      setShowReplyBox(null);
    } catch (error) {
      Toast.fail('回复失败，请稍后再试');
    }
  };

  return (
    <div className="comment-component">
      <PullRefresh onRefresh={onRefresh}>
        <List
          className="comment-list"
          finished={finish}
          onLoad={onLoad}
          finishedText="没有更多评论了"
          errorText="加载失败，点击重试"
        >
          {comments.map((comment) => (
            <div key={comment.id} className="comment-card">
              {/* 用户信息 */}
              <div className="comment-header">
                <div className="user-info">
                  <img
                    src={comment.accountAvatar ?? getDefaultAvatarPath()}
                    alt={comment.accountName}
                    className="user-avatar"
                  />
                  <div className="user-details">
                    <div className="user-name">{comment.accountName}</div>
                    <div className="user-time">{comment.createTimeStr}</div>
                  </div>
                </div>
                <div className="user-rating">
                  {Array(comment.rate)
                    .fill(0)
                    .map((_, i) => (
                      <i key={i} className="fa fa-star"></i>
                    ))}
                </div>
              </div>

              {/* 评论内容 */}
              <div className="comment-content">{comment.content}</div>

              {/* 评论图片 */}
              {comment.sources.length > 0 && (
                <div className="comment-images">
                  <div className="image-grid">
                    {comment.sources.slice(0, 3).map((source, index) => (
                      <div
                        key={source.id}
                        className="image-item"
                        onClick={() =>
                          handleImageClick(
                            comment.sources.map((s) => s.path),
                            index
                          )
                        }
                      >
                        <img src={source.path} alt={source.fileName} />
                      </div>
                    ))}
                    {comment.sources.length > 3 && (
                      <div
                        className="image-more"
                        onClick={() =>
                          handleImageClick(
                            comment.sources.map((s) => s.path),
                            0
                          )
                        }
                      >
                        <span>+{comment.sources.length - 3}</span>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 回复列表 */}
              {comment.replays.length > 0 && (
                <div className="replies-container">
                  {comment.replays.map((replay) => (
                    <div key={replay.id} className="reply-item">
                      <div className="reply-header">
                        <img
                          src={replay.accountAvatar || getDefaultAvatarPath()}
                          alt={replay.accountName}
                          className="reply-avatar"
                        />
                        <div className="reply-user">
                          <div className="reply-name">{replay.accountName}</div>
                          {replay.commentAccountName && (
                            <div className="reply-to">回复 {replay.commentAccountName}</div>
                          )}
                          <div className="reply-time">{replay.createTimeStr}</div>
                        </div>
                      </div>
                      <div className="reply-content">{replay.content}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* 回复框 */}
              {showReplyBox === comment.id && (
                <div className="reply-box">
                  <textarea
                    value={replyContent}
                    onChange={(e) => setReplyContent(e.target.value)}
                    placeholder="写下你的回复..."
                    className="reply-input"
                    rows={2}
                  />
                  <div className="reply-actions">
                    <Button
                      type="primary"
                      size="small"
                      onClick={() => handleSubmitReply(comment.id, comment.accountName)}
                      disabled={!replyContent.trim()}
                      className="reply-button"
                    >
                      回复
                    </Button>
                    <Button size="small" onClick={() => handleReply(showReplyBox)}>
                      取消
                    </Button>
                  </div>
                </div>
              )}

              {/* 回复按钮 */}
              {showReplyBox !== comment.id && (
                <div className="comment-actions">
                  <Button
                    size="small"
                    onClick={() => handleReply(comment.id)}
                    className="reply-btn"
                  >
                    回复
                  </Button>
                </div>
              )}
            </div>
          ))}
        </List>
      </PullRefresh>

      {/* 图片预览 */}
      <ImagePreview
        visible={showPreview}
        images={previewImages}
        startPosition={initialPosition}
        onClose={() => setShowPreview(false)}
      />
    </div>
  );
};

export default CommentComponent;
